package com.wsm.kotlintest.viewmodel.fragment

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList
import com.wsm.kotlintest.model.datafactory.DataMaker
import com.wsm.kotlintest.common.LOAD_MORE_STATE_DEFAULT
import com.wsm.kotlintest.common.isNetworkAvailable
import com.wsm.kotlintest.model.response.redditResponseModel.Children

class DataFragmentViewModel : ViewModel() {

    var isRefreshing = MutableLiveData<Boolean>()

    var netState = MutableLiveData<Boolean>()

    var loadMoreState = MutableLiveData<Int>().apply { value = LOAD_MORE_STATE_DEFAULT }

    var dataList = LivePagedListBuilder<String, Children>(
            DataMaker(netState, isRefreshing, loadMoreState),
            PagedList.Config.Builder().setPageSize(10).setEnablePlaceholders(false).setInitialLoadSizeHint(30).build()).build()

    fun retry() {
        /*这里判断一下，看是否有网
        * 如果没网导致出现的ERROR PAGE，
        * 很大概率现在也没网，点了重试也白点*/
        if (isNetworkAvailable() && !(isRefreshing.value as Boolean)) {
            isRefreshing.value = true
            netState.value = true
            (dataList.value?.dataSource as DataMaker.MyData).invalidate()
        }
    }
}